package com.dianrui.moonfire.util;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */

public class PhoneCode extends ContentObserver {
    private Context mContext; // 上下文
    private String code; // 验证码
    SmsListener mListener;
    private String mPhone;
    Cursor mCursor;

    public PhoneCode(Context context, Handler handler, String phone, SmsListener listener) {
        super(handler);
        this.mContext = context;
        this.mPhone = phone;
        this.mListener = listener;
    }

    public PhoneCode(Context context, Handler handler, SmsListener listener) {
        super(handler);
        this.mContext = context;
        this.mListener = listener;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange);
        // 第一次回调 不是我们想要的 直接返回
        //content://sms/raw/4
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        // 第二次回调 查询收件箱里的内容
        Uri inboxUri = Uri.parse("content://sms/inbox");

        // 按时间顺序排序短信数据库
        mCursor = mContext.getContentResolver().query(inboxUri, new String[]{"_id", "address", "read", "body"}, null,
                null, "_id desc");
        try {
            if (mCursor != null) {
                if (mCursor.moveToFirst()) {
                    // 获取短信内容
                    String body = mCursor.getString(mCursor.getColumnIndex("body"));
                    Log.e("获取短信内容----->", body);
                    String regEx = "(\\d{6})";
                    Pattern pattern = Pattern.compile(regEx);
                    Matcher matcher = pattern.matcher(body);
                    while (matcher.find()) {
                        code = matcher.group();
                        if (mListener != null) {
                            mListener.onResult(matcher.group());
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (mCursor != null) {
                mCursor.close();
            }

        }


    }

    /**
     * 短信回调接口
     */
    public interface SmsListener {
        /**
         * @param result 回调内容（验证码）
         */
        void onResult(String result);
    }
}
